package com.starbaba.system.index;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;

import com.google.gson.JsonObject;
import com.opensymphony.xwork2.Action;
import com.starbaba.common.ResultJson;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.SpringContextManager;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.constant.Constants;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.core.web.tree.MenuTreeBuilder;
import com.starbaba.system.menu.model.MenuVO;
import com.starbaba.system.user.model.UserVO;
import com.starbaba.system.userauthority.service.AuthService;

@SuppressWarnings({"serial","unchecked","rawtypes","unused"})
public class AuthorityAction extends BaseAction {
	public final static String PAGE_USER_ID = "userId";
	public final static String PAGE_USER_PASSWORD = "password";
	public final static String PAGE_AUTO_LOGIN = "autologin";
	public AuthService authService;
	public Map<String, Object> paramsMap = new HashMap<String, Object>();
	private String treeJson;

	public String login() {
		authService = SpringContextManager.getBean("authServiceImpl");
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String userId = (String) paramsMap.get(PAGE_USER_ID);
		String password = (String) paramsMap.get(PAGE_USER_PASSWORD);
		String autologin = (String) paramsMap.get(PAGE_AUTO_LOGIN);
		String vcode = "";
		try {
			vcode = (String) paramsMap.get("valicode");

			if (!StringUtils.isEmpty(vcode)) {
				System.out.println("================vcode=" + vcode);
				Constants.ISNEEDVOLICODE = true;
			}
			return authService.login(userId, password, vcode, autologin);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			this.addActionError(ex.getMessage());
			return Action.ERROR;
		}
	}
 
	public List<TreeMap<String, List<MenuVO>>> getMenuList() {
		authService = SpringContextManager.getBean("authServiceImpl");
		List<MenuVO> thirdChildMenuList = new ArrayList<MenuVO>();
		UserVO userVO = authService.getOperator();
		// 一次全部查出来 管理员
		List<MenuVO> menuVOs;
		if (userVO.getIsManager()) {
			menuVOs = authService.queryMenuAll();
		} else {
			menuVOs = authService.queryMenuByGroupids(userVO.getGourpIdList());
		}
		int minMenuType = authService.MaxMenuType(menuVOs);
		List<TreeMap<String, List<MenuVO>>> menuSubsMaps = reMenu(new ArrayList<TreeMap<String, List<MenuVO>>>(),
				menuVOs, minMenuType, 1);
		return menuSubsMaps;
	}

	@Override
	public String execute() {
		// authService = SpringContextManager.getBean("authServiceImpl");
		// List<MenuVO> thirdChildMenuList = new ArrayList<MenuVO>();
		// UserVO userVO = authService.getOperator();
		// userVO.getGourpIdList();//获取groupid
		List groupids = null;
		try {
			if (null == userVO) {
				this.addErrorMessage(Constants.ERRORMESSAGE_4);
				return Action.ERROR;
			}
			// 开始 建造菜单树

			// List<MenuVO> firMenuList = authService.queryTopMenu(userVO,
			// groupids, "1", "0");
			//
			// TreeMap<String, List<MenuVO>> rootMenuSubsMap = new
			// TreeMap<String, List<MenuVO>>(); TreeMap<String, List<MenuVO>>
			// rootChildMenuSubsMap = new TreeMap<String, List<MenuVO>>(); for
			// (MenuVO menuVO : firMenuList) { String menuId =
			// menuVO.getControlid(); List<MenuVO> secondChildMenuList =
			// authService.querySecondChildMenu(userVO, menuId, groupids, "1",
			// "0"); for (MenuVO vo : secondChildMenuList) { String secondMenuId
			// = vo.getControlid(); thirdChildMenuList =
			// authService.queryThirdChildMenu(userVO, secondMenuId, groupids,
			// "1", "0"); if (!thirdChildMenuList.isEmpty()) {
			// rootChildMenuSubsMap.put(secondMenuId, thirdChildMenuList); } }
			// rootMenuSubsMap.put(menuId, secondChildMenuList); }

			// 返回菜单树
			List<TreeMap<String, List<MenuVO>>> menuSubsMaps = getMenuList();
			String contentPath = Struts2Utils.getRequest().getContextPath();
			// treeJson = MenuTreeBuilder.buildTree(firMenuList,
			// rootMenuSubsMap, rootChildMenuSubsMap, contentPath);
			treeJson = MenuTreeBuilder.buildTree2(menuSubsMaps, contentPath);
		} catch (Exception ex) {
			this.addErrorMessage(Constants.ERRORMESSAGE_5);
			log.error(Constants.ERRORMESSAGE_5, ex);
			return Action.ERROR;
		}
		return Action.SUCCESS;
	}

	/**
	 * 根据列表菜单返回菜单树
	 * 
	 * @param resList
	 *            目的容器
	 * @param menuVOs
	 *            数据源
	 * @param minMenuType
	 *            最低级别
	 * @param index
	 *            当前级别
	 * @return
	 */
	public List<TreeMap<String, List<MenuVO>>> reMenu(List<TreeMap<String, List<MenuVO>>> resList,
			List<MenuVO> menuVOs, int minMenuType, int index) {
		if (index > minMenuType + 1) {
			return resList;
		}

		TreeMap<String, List<MenuVO>> treeMap = new TreeMap<String, List<MenuVO>>();// 该级别树结构
		List<MenuVO> list = new ArrayList<>();
		if (index == 1) {
			resList = new ArrayList<>();
			String pid = "00";
			for (MenuVO menuVO : menuVOs) {
				if (pid.equals(menuVO.getPcontrolid())) {
					list.add(menuVO);
				}
			}
			treeMap.put(pid, list);
		} else {
			Set<String> pids = getPids(resList.get(resList.size() - 1));
			for (String pid : pids) {
				for (MenuVO menuVO : menuVOs) {
					if (pid.equals(menuVO.getPcontrolid())) {
						list.add(menuVO);
					}
				}
				treeMap.put(pid, list);
			}
		}
		resList.add(treeMap);
		return reMenu(resList, menuVOs, minMenuType, ++index);
	}

	public Set<String> getPids(TreeMap<String, List<MenuVO>> map) {
		Set<String> pids = new HashSet();
		for (Entry<String, List<MenuVO>> entry : map.entrySet()) {
			for (MenuVO menuVO : entry.getValue()) {
				pids.add(menuVO.getControlid());
			}
		}
		return pids;
	}

	/*
	 * 查询用户权限type为1--查询所有菜单,为0--查询该用户权限菜单
	 */
	public String executeGetList(Integer type, List groupids, String from) {
		authService = SpringContextManager.getBean("authServiceImpl");
		List<MenuVO> firMenuList = new ArrayList<MenuVO>();
		List<MenuVO> secondChildMenuList = new ArrayList<MenuVO>();
		List<MenuVO> thirdChildMenuList = new ArrayList<MenuVO>();
		List<MenuVO> secondChildMenuListToPut = new ArrayList<MenuVO>();
		List<MenuVO> thirdChildMenuListToPut = new ArrayList<MenuVO>();
		UserVO userVO = authService.getOperator();
		try {
			if (null == userVO) {
				this.addErrorMessage(Constants.ERRORMESSAGE_4);
				return Action.ERROR;
			}
			if (type == 1) {
				firMenuList = authService.queryTopMenuAll(userVO);
			} else {
				firMenuList = authService.queryTopMenu(userVO, groupids, "0", from);
			}
			TreeMap<String, List<MenuVO>> rootMenuSubsMap = new TreeMap<String, List<MenuVO>>();
			TreeMap<String, List<MenuVO>> rootChildMenuSubsMap = new TreeMap<String, List<MenuVO>>();
			for (MenuVO menuVO : firMenuList) {
				String menuId = menuVO.getControlid();
				if (type == 1) {
					secondChildMenuList = authService.querySecondChildMenuAll(userVO, menuId);
				} else {
					secondChildMenuList = authService.querySecondChildMenu(userVO, menuId, groupids, "0", from);
				}
				secondChildMenuListToPut.addAll(secondChildMenuList);
				for (MenuVO vo : secondChildMenuList) {
					String secondMenuId = vo.getControlid();
					if (type == 1) {
						thirdChildMenuList = authService.queryThirdChildMenuAll(userVO, secondMenuId);
					} else {
						thirdChildMenuList = authService.queryThirdChildMenu(userVO, secondMenuId, groupids, "0", from);
					}
					if (!thirdChildMenuList.isEmpty()) {
						thirdChildMenuListToPut.addAll(thirdChildMenuList);
						rootChildMenuSubsMap.put(secondMenuId, thirdChildMenuList);
					}
				}
				rootMenuSubsMap.put(menuId, secondChildMenuList);
			}
			// begin
			// List<MenuVO> menuVOs;
			// if (userVO.getIsManager()) {
			// menuVOs = authService.queryMenuAll();
			// } else {
			// menuVOs =
			// authService.queryMenuByGroupids(userVO.getGourpIdList());
			// }
			// int minMenuType = authService.MaxMenuType(menuVOs);
			// List<TreeMap<String, List<MenuVO>>> menuSubsMaps = reMenu(new
			// ArrayList<TreeMap<String, List<MenuVO>>>(),
			// menuVOs, minMenuType, 1);
			//
			// List<MenuVO> list = new ArrayList<>();
			// int len = 0;
			// for (int j = 0; j < len; j++) {
			// TreeMap<String, List<MenuVO>> treeMap = menuSubsMaps.get(j);//
			// 当前级别的所有记录
			// }

			// end

			String firMenuListJsonStr = JsonUtils.toJson(firMenuList, null, false, null, false);// 一级列表
			String secMenuListJsonStr = JsonUtils.toJson(secondChildMenuListToPut, null, false, null, false);
			String thiMenuListJsonStr = JsonUtils.toJson(thirdChildMenuListToPut, null, false, null, false);
			String jsonStr = "{\"firstMenu\": " + firMenuListJsonStr + ", \"secondMenu\": " + secMenuListJsonStr
					+ ", \"thirdMenu\": " + thiMenuListJsonStr + "}";

			jsonStr = JsonUtils.toJson(jsonStr, null, false, null, false);
			return jsonStr;

		} catch (Exception ex) {
			this.addErrorMessage(Constants.ERRORMESSAGE_5);
			log.error(Constants.ERRORMESSAGE_5, ex);
			return Action.ERROR;
		}
	}

	public String changeAuth(List menuList, String groupid, String type, String creator) {
		authService = SpringContextManager.getBean("authServiceImpl");
		try {
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			if (Integer.valueOf(type) == 1) {
				// 新增
				authService.addUserMenuList(menuList, groupid, creator);
				resultJs.msg = "添加成功";
			} else {
				// 删除
				authService.delUserMenuList(menuList, groupid);
				resultJs.msg = "删除成功";
			}

			result.add("result", resultJs.toJSON());
			return result.toString();
		} catch (Exception ex) {
			this.addErrorMessage(Constants.ERRORMESSAGE_5);
			log.error(Constants.ERRORMESSAGE_5, ex);
			return Action.ERROR;
		}
	}

	public String logout() {
		authService = SpringContextManager.getBean("authServiceImpl");
		Object loginObj = authService.getOperator();
		return authService.logout(loginObj);
	}

	public String getTreeJson() {
		return treeJson;
	}

	public void setTreeJson(String treeJson) {
		this.treeJson = treeJson;
	}

	public String ListToString(List<?> list) {
		StringBuffer sb = new StringBuffer();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i) == null || list.get(i) == "") {
					continue;
				}
				if (list.get(i) instanceof List) {
					sb.append(ListToString((List<?>) list.get(i)));
					sb.append(",");
				} else {
					sb.append(list.get(i));
					sb.append(",");
				}
			}
		}
		return sb.toString();
	}

}